import { Injectable } from "@nestjs/common";
import { AbilityBuilder, createMongoAbility } from '@casl/ability'
import { Menus } from "src/menus/entities/menu.entity";
import { UserService } from "src/user/user.service";
import caslAction from "src/untils/caslAction";
@Injectable()
export class CaslAbilityService {
    constructor(
        private userService:UserService
    ){}

    // 针对整个系统的权限控制
    async forRoot(username:string){
        const { can , cannot , build } = new AbilityBuilder(createMongoAbility)

        //  can函数的两个参数 
        //  第一个参数  路由信息的meta  包含了acl  就是action信息
        //  第二个参数 访问的模块
        // can('read' , Menus)
        // cannot('update' , Menus)

        const user = await this.userService.findByUsername(username)
        user.roles.forEach((role)=>{
            role.menus.forEach((menu)=>{
                const actions = menu.acl.split(',')
                actions.forEach((action)=>{
                    console.log(action , caslAction(menu.path));
                    can(action , caslAction(menu.path) )  // all 是 CASL 中的一个特殊关键字，代表 "任何科目"。
                    // can(action , 'all') 
                })
            })
        })

        const ability = build({
            detectSubjectType:(object:any) => object.constructor
        })

        return ability

    }
}